<script lang="ts" setup>
import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table'

import { defineEmits, ref, watch } from 'vue'

import { useVbenModal } from '@vben/common-ui'
import { AntPlusOutlined } from '@vben/icons'

import { useDebounceFn } from '@vueuse/core'
import { Button, Divider, Input, message, Switch } from 'ant-design-vue'
import dayjs from 'dayjs'

import { useVbenForm } from '#/adapter/form'
import { useVbenVxeGrid } from '#/adapter/vxe-table'
import { getAdminList, getCompanyList, getDict, getSupplyList } from '#/api/common'
import { doRevicedRecordAdd, doRevicedRecordAgainst, doRevicedRecordApproval, doRevicedRecordEdit, getRevicedRecordDetailEditInfo } from '#/api/revicedRecord'

import PurchaseBom from '../../modules/purchaseBom.vue'
import PurchaseModal from '../../modules/purchaseModal.vue'
import Warehouse from '../../modules/warehouse.vue'

interface RowType {
  confirm_num?: number | string
  price?: number | string
  dead_line?: string
  template_no?: string
  material_use?: string
  single_piece?: number | string
  other_pay_remark?: string
  remark?: string
  material_id?: string
  material_name?: string
  material_sku_id?: number
  unit?: string
  action_num?: number
  gift_num?: number
  finish?: boolean
  less_num?: number
  total_price?: string
  product_sn?: string
  RevicedRecord_bom_detail_id?: number
  _X_ROW_KEY?: string
}

const emit = defineEmits(['fetchData'])

const RecordId = ref<number>()
const routerData = ref<any>({})
const formData = ref<any>({})
const dict = ref<any>({})
const adminList = ref<any>([])
const companyList = ref<any>([])
const submitLoading = ref(false)

const isDisabled = ref(true)
const keyword = ref<Record<string, string>>({
  warehouse_id: '',
  supply_id: '',
})

const handleAgainstToApproval = async (type: string) => {
  try {
    await (type === 'approval' ? doRevicedRecordApproval({ ids: [RecordId.value] }) : doRevicedRecordAgainst({ ids: [RecordId.value] }))
    message.success('操作成功')
    emit('fetchData')
    modalApi.close()
  } catch {}
}

const fetchData = async () => {
  const { row } = await getRevicedRecordDetailEditInfo({
    record_id: RecordId.value,
  })
  formApi.setValues(row)
  formData.value = { ...row } // 保留对旧逻辑的兼容

  Object.keys(keyword.value).forEach((key: string) => {
    if (row[key]) {
      keyword.value[key] = `initValue:${row[key]}`
    }
  })

  // 使用 setGridOptions 更新表格数据
  if (gridApi) {
    gridApi.setGridOptions({
      data: row.bom_list || [],
    })
  }
  // 初始化时根据结算方式设置结算规则的禁用状态
  updatePaymentRuleDisabledState()
}

// 获取供应商选项
const supplyOptions = async ({ keyword = '' }: Record<string, any>) => {
  let quick_search = ''
  let initValue = ''
  const initKey = 'SupplyName'

  if (keyword.startsWith('initValue:')) {
    initValue = keyword.replace('initValue:', '')
  } else {
    quick_search = keyword
  }

  const { list } = await getSupplyList({
    quick_search,
    page: 1,
    limit: 30,
    initKey,
    initValue,
    select: true,
  })

  return list.map((item: any) => ({
    label: item.SupplyNa,
    value: item.SupplyName,
  }))
}

const initClear = async () => {
  RecordId.value = 0
  formData.value = {}
  if (gridApi) {
    gridApi.setGridOptions({
      data: [],
    })
  }
  Object.keys(keyword.value).forEach((key: string) => {
    keyword.value[key] = ''
  })
}
const init = async () => {
  const { select_list } = await getDict({
    keys: ['paymentMethod', 'paymentRule'],
    type: 2,
  })
  dict.value = select_list

  const { list: adminApi } = await getAdminList({
    select: true,
    limit: 9999,
    group_id: 7,
  })
  adminList.value = adminApi

  const companyApi = await getCompanyList({})
  companyList.value = companyApi
}

// 当结算方式改变时，更新结算规则的禁用状态
const updatePaymentRuleDisabledState = () => {
  if (!dict.value.paymentRule || !formData.value.fk_type) return

  dict.value.paymentRule.forEach((item: any) => {
    item.disabled = item.value !== formData.value.fk_type
  })
}

// 监听结算方式变化
watch(
  () => formData.value.fk_type,
  () => {
    updatePaymentRuleDisabledState()

    // 如果当前选中的结算规则被禁用了，则清空结算规则的选择
    const currentRule = dict.value.paymentRule?.find((item: any) => item.name === formData.value.fk_rule && item.disabled)

    if (currentRule) {
      formData.value.fk_rule = undefined
    }
  },
)

watch(isDisabled, (val) => {
  formApi.setState({ commonConfig: { disabled: val } })
})

const [Modal, modalApi] = useVbenModal({
  class: 'w-5/6',
  appendToMain: true,
  fullscreen: true,
  showConfirmButton: false,
  showCancelButton: false,
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      routerData.value = modalApi.getData<Record<string, any>>()
      initClear()
      init()
      if (routerData.value?.info?.record_id) {
        RecordId.value = routerData.value?.info?.record_id
      }

      if (RecordId.value) {
        fetchData()
        disabledOn()
      } else {
        disabledOff()
      }
    }
  },
})

const gridOptions: VxeGridProps<RowType> = {
  pagerConfig: {
    enabled: false,
  },
  cellStyle({ column }) {
    if (column.field === 'dead_line') {
      return {
        color: 'red',
      }
    }
  },
  columns: [
    { type: 'seq', width: 90, title: '编号' },
    {
      field: 'purchase_bom_detail_id',
      title: '选择物料',
      width: 310,
      visible: false,
    },
    { field: 'material_name', title: '选择物料', width: 310 },
    { field: 'less_num', title: '应收', width: 90 },
    {
      field: 'action_num',
      title: '数量',
      width: 100,
      editRender: {},
      slots: { edit: 'action_num_edit' },
    },
    {
      field: 'gift_num',
      title: '赠送数量',
      width: 100,
      editRender: {},
      slots: { edit: 'gift_num_edit' },
    },
    {
      field: 'finish',
      title: '是否完成',
      width: 100,
      editRender: {},
      slots: { default: 'finish', edit: 'finish_edit' },
    },
    { field: 'confirm_num', title: '下单数量', width: 90 },
    { field: 'reviced_num', title: '收料数量', width: 90 },
    { field: 'unit', title: '单位', width: 70 },
    { field: 'price', title: '单价', width: 80 },
    { field: 'total_price', title: '总价', width: 150 },
    { field: 'product_sn', title: '制单号', width: 120 },
    {
      field: 'remark',
      title: '备注',
      width: 100,
      editRender: {},
      slots: { edit: 'remark_edit' },
    },
    {
      field: 'operation',
      fixed: 'right',
      slots: { default: 'operation' },
      title: '操作',
      width: 140,
    },
  ],
  exportConfig: {},
  editConfig: {
    mode: 'cell',
    trigger: 'click',
    showStatus: true,
  },
  height: '500px',
  keepSource: true,
  data: [],
  showOverflow: false,
}

const disabledOn = async () => {
  isDisabled.value = true
  formApi.setState({ commonConfig: { disabled: true } })
}
const disabledOff = async () => {
  isDisabled.value = false
  formApi.setState({ commonConfig: { disabled: false } })
}

const handleRowDelete = async (row: RowType) => {
  if (gridApi) {
    const currentData = gridApi.grid.getData()
    const index = currentData.findIndex((item: any) => item._X_ROW_KEY === row._X_ROW_KEY)
    if (index !== -1) {
      currentData.splice(index, 1)
      gridApi.setGridOptions({
        data: currentData,
      })
    }
  }
}

const opendAddSku = async () => {
  const saveData = await formApi.getValues()
  console.log(saveData.purchase_id)
  if (!saveData.purchase_id) {
    message.warning('请选择采购单')
    return false
  }
  SkuModalApi.setData({
    query: { purchase_id: saveData.purchase_id, in_stock: 0 },
  }).open()
}

const shareData = (res: any) => {
  console.log('shareData', res)
  if (res.shareType && res.shareType === 'warehouse') {
    doWarehouseList(res)
  } else if (res.shareType && res.shareType === 'purchase') {
    doPurchaseList(res)
  } else {
    doMaterialList(res)
  }
}

const doWarehouseList = (res: any) => {
  if (res.list && res.list.length > 0) {
    const warehouse = res.list[0]
    formApi.setValues({
      ware_house_id: warehouse.id,
      in_ware_house_id: warehouse.code_name,
    })
  }
}

const doPurchaseList = (res: any) => {
  if (res.list && res.list.length > 0) {
    const purchase = res.list[0]
    formApi.setValues({
      purchase_id: purchase.purchase_id,
      purchase_sn: purchase.purchase_sn,
      supply_id: purchase.supply_id,
      supply_name: purchase.supply_name,
    })
  }
}
const doMaterialList = (res: any) => {
  if (res.list && res.list.length > 0) {
    // 获取当前表格数据
    const currentTableData = gridApi.grid.getData() || []

    // 将选中的物料数据转换为表格需要的格式
    const newRows = res.list.map((item: any) => ({
      purchase_bom_detail_id: item.purchase_bom_detail_id, // 物料ID
      material_sku_id: item.material_sku_id, // 物料skuID
      material_id: item.material_id, // 物料ID
      material_name: item.material_name, // 物料名称
      action_num: 0, // 数量
      price: item.price || 0, // 物料单价，默认为0
      total_price: item.price, // 总价
      unit: item.unit, // 单位
      unit_rate: item.unit_rate, // 换算比例
      stock: item.stock, // 库存
      cloth_width: item.cloth_width, // 幅宽
      gram_weight: item.gram_weight, // 克重
      remark: '', // 备注，默认为空
      less_num: item.less_num, // 应收数量
      confirm_num: item.confirm_num, // 应收数量
      reviced_num: item.reviced_num, // 已收数量
      gift_num: 0, // 赠送数量
      finish: 0, // 是否完成
    }))

    // 合并现有数据和新数据
    const updatedTableData = [...currentTableData, ...newRows]

    // 更新表格数据
    gridApi.setGridOptions({
      data: updatedTableData,
    })
    message.success(`成功添加 ${res.list.length} 条物料`)
  } else {
    message.warning('未选择任何物料')
  }
}

async function onSubmit() {
  const { valid } = await formApi.validate()
  if (valid) {
    submitLoading.value = true
    try {
      const saveData = await formApi.getValues()
      if (gridApi) {
        const tableData = gridApi.grid.getData()
        saveData.bom_list = tableData
      }
      if (RecordId.value) {
        doRevicedRecordEdit({ ...saveData, record_id: RecordId.value }).then((res) => {
          if (res.data.code === 1) {
            message.success('保存成功')
            emit('fetchData')
            modalApi.close()
          } else {
            message.error(res.data.msg)
          }
        })
      } else {
        doRevicedRecordAdd(saveData).then((res) => {
          if (res.data.code === 1) {
            message.success('保存成功')
            emit('fetchData')
            modalApi.close()
          } else {
            message.error(res.data.msg)
          }
        })
      }
    } finally {
      submitLoading.value = false
    }
  }
}

const handleSubmit = useDebounceFn(async () => {
  await onSubmit()
}, 300)
const [Form, formApi] = useVbenForm({
  commonConfig: {
    disabled: isDisabled.value,
    componentProps: {
      class: 'w-full',
    },
  },
  showDefaultActions: false,
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      fieldName: 'record_sn',
      label: '收料单号',
      componentProps: {
        disabled: true,
        placeholder: '自动生成',
      },
    },
    {
      component: 'Input',
      fieldName: 'ware_house_id',
      label: '仓库ID',
      formItemClass: 'hidden',
    },
    {
      component: 'Input',
      fieldName: 'in_ware_house_id',
      label: '仓库',
      componentProps: () => ({
        onClick: (value: any) => {
          WarehouseApi.setData({
            query: { params: { type: '物料', is_stop: 0 } },
            selectType: 'radio',
          }).open()
        },
      }),
      rules: 'required',
    },
    {
      component: 'Input',
      fieldName: 'purchase_sn',
      label: '采购单',
      componentProps: () => ({
        placeholder: '请选择采购单',
        onClick: (value: any) => {
          PurchaseModalApi.setData({ query: {}, selectType: 'radio' }).open()
        },
      }),
      rules: 'required',
    },
    {
      component: 'Input',
      fieldName: 'purchase_id',
      label: '采购单ID',
      formItemClass: 'hidden',
    },
    {
      component: 'Input',
      fieldName: 'supply_name',
      label: '供应商(采购单)',
      disabled: true,
      componentProps: () => ({
        placeholder: '请选择采购单',
      }),
    },
    {
      component: 'Input',
      fieldName: 'supply_id',
      label: 'supply_id',
      formItemClass: 'hidden',
    },
    {
      component: 'DatePicker',
      fieldName: 'record_date',
      label: '单据日期',
      defaultValue: dayjs().format('YYYY-MM-DD'),
      componentProps: {
        class: 'w-full',
        type: 'date',
        clearable: true,
        placeholder: '请选择单据日期',
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        disabledDate: (current: any) => {
          // 不允许选择三天前之前的数据
          return current && current <= dayjs().subtract(4, 'day').startOf('day')
        },
      },
    },
    {
      component: 'Input',
      fieldName: 'product_sn',
      label: '生产单',
      componentProps: {
        placeholder: '请选择生产单',
      },
    },
    {
      component: 'Input',
      fieldName: 'remark',
      label: '备注',
      componentProps: {
        placeholder: '请输入备注',
      },
    },
  ],
  wrapperClass: 'grid grid-cols-6',
})
const gridEvents: VxeGridListeners<RowType> = {
  cellClick: ({ row }) => {
    // message.info(`cell-click: ${row.material_name}`);
  },
  editClosed: (res) => {
    if (res.column.field === 'action_num') {
      const row = res.row
      const actionNum = Number(row.action_num) || 0
      const price = Number(row.price) || 0
      row.total_price = (actionNum * price).toFixed(2)
    }
  },
}

const [Grid, gridApi] = useVbenVxeGrid({
  gridEvents,
  gridOptions,
})

const [SkuModal, SkuModalApi] = useVbenModal({
  connectedComponent: PurchaseBom,
})

const [WarehouseModal, WarehouseApi] = useVbenModal({
  connectedComponent: Warehouse,
})

const [PurchaseModalComp, PurchaseModalApi] = useVbenModal({
  connectedComponent: PurchaseModal,
})
</script>
<template>
  <Modal title="收料单">
    <div class="p-4">
      <Form />
      <Divider />
      <div class="mb-2 flex items-center justify-between">
        <h3 class="text-lg font-medium">物料列表</h3>
        <Button :disabled="isDisabled" type="primary" @click="opendAddSku()">
          <AntPlusOutlined />
          新增物料
        </Button>
      </div>

      <Grid>
        <template #operation="{ row }">
          <Button :disabled="isDisabled" danger size="small" @click="handleRowDelete(row)">删除</Button>
        </template>
        <template #action_num_edit="{ row }">
          <Input v-model:value="row.action_num" :disabled="isDisabled" />
        </template>
        <template #gift_num_edit="{ row }">
          <Input v-model:value="row.gift_num" :disabled="isDisabled" />
        </template>
        <template #finish="{ row }">
          <span v-if="row.finish || row.finish != false">是</span>
          <span v-else>否</span>
        </template>
        <template #finish_edit="{ row }">
          <!-- <Switch :disabled="isDisabled" v-model:checked="row.finish" checkedValue="1" unCheckedValue="0" /> -->
          <Switch :disabled="isDisabled" v-model:checked="row.finish" />
        </template>
        <template #remark_edit="{ row }">
          <Input v-model:value="row.remark" :disabled="isDisabled" />
        </template>
      </Grid>
    </div>
    <template #prepend-footer>
      <div>
        <Button @click="modalApi.close()">取消</Button>
      </div>
      <div class="space-x-2">
        <template v-if="RecordId && isDisabled">
          <Button type="ghost" class="bg-[#f56c6c] text-white hover:opacity-75" @click="handleAgainstToApproval(formData.posted ? 'against' : 'approval')">
            {{ formData.posted ? '反审' : '审核' }}
          </Button>
          <Button type="ghost" v-if="!formData.posted" class="bg-[#f0a62f] text-[#fff] hover:opacity-75" @click="disabledOff()">修改</Button>
        </template>
        <Button v-if="!isDisabled || !RecordId" type="primary" :loading="submitLoading" :disabled="submitLoading" @click="handleSubmit">保存</Button>
      </div>
    </template>

    <SkuModal @share-data="shareData" />
    <WarehouseModal @share-data="shareData" />
    <PurchaseModalComp @share-data="shareData" />
  </Modal>
</template>

<style lang="scss" scoped>
.fixed-width-select {
  width: 160px;
}
</style>
